package mk.company.fin.main;

import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.UIManager;

import mk.company.fin.frame.FinFrame;
import mk.company.fin.thread.StartApplication;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The main application wrapper.
 * 
 * @author vlado.gjorgjiev
 */
public class GuiApplication {
	
	private static final Logger LOG = LoggerFactory.getLogger(MainClass.class);
	public static final double SPLIT_DEVIDER_LOCATION = 0.75;
	
	private FinFrame finFrame;
	private Thread thread;

	
	/**
	 * Default constructor.
	 */
	public GuiApplication() {
		try {

			for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
		} catch (Exception e) {
			try{
				UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
			}
			catch (Exception ex){
				LOG.warn("Can't set the system look and feel", e);
			}
		}
		finFrame = new FinFrame();
		finFrame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent windowevent) {
				if (thread.isAlive()) {
					thread.interrupt();
				}
				finFrame.dispose();
				System.exit(0);
			}
		});
		
		finFrame.addComponentListener(new ComponentAdapter() {
			@Override
			public void componentResized(ComponentEvent componentevent) {
				if (finFrame.getSplitPane() != null) {
					finFrame.getSplitPane().setDividerLocation(SPLIT_DEVIDER_LOCATION);
				}
			}
		});
	}
	
	
	/**
	 * Creates the GUI application.
	 */
	public void displayGui() {
		Icon loadImage = new ImageIcon(this.getClass().getResource("/files/loading.gif"));
		JLabel loadLabel = new JLabel(loadImage);
		finFrame.getContentPane().add(loadLabel);
        finFrame.pack();
        finFrame.setVisible(true);
        finFrame.setLocationRelativeTo(null);
        
        // go with thread
        StartApplication startApp = new StartApplication(finFrame, loadLabel);
        thread = new Thread(startApp);
        thread.start();
	}

}
